<?php
namespace app\api\controller\service;

use app\common\controller\Api;

/**
 * 首页接口
 */
class Address extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * 获取地址列表
     * @return void
     * @throws \think\exception\DbException
     */
    public function addressList()
    {
        $uid = $this->auth->id;
        $page = input('page/d',1);
        $limit = 10;
        $list = model('app\api\model\service\Address')
            ->where('user_id', $uid)
            ->field('id,user_id,province,city,district,area,address,lng,lat,state,name,mobile,sex')
            ->order('state desc,id desc')
            ->page($page)
            ->limit($limit)
            ->select();
        $this->success('返回成功', $list);
    }

    /**
     * 地址操作
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function handleAddress()
    {
        $uid = $this->auth->id;
        $post = input('post.','','trim,strip_tags');
        if($post['type'] == 'add')
        {
            $post['user_id'] = $uid;
            $address = new \app\api\model\service\Address($post);
            $address->allowField(true)->save();
            if($post['state'] == 1)
            {
                model('app\api\model\service\Address')->where(['state'=>1,'id'=>['<>',$address->id],'user_id'=>$uid])->update(['state'=>0]);
            }
            $this->success('地址添加成功');
        }elseif($post['type'] == 'edit')
        {
            $info = model('app\api\model\service\Address')->where(['id'=>$post['id'],'user_id'=>$uid])->find();
            !$info && $this->error('地址信息异常');
            $address = new \app\api\model\service\Address();
            $address->allowField(true)->save($post,['id'=>$post['id']]);
            if($info['state'] == 0 && $post['state'] == 1)
            {
                model('app\api\model\service\Address')->where(['state'=>1,'id'=>['<>',$post['id']],'user_id'=>$uid])->update(['state'=>0]);
            }
            $this->success('信息已更新');
        }elseif ($post['type'] == 'del')
        {
            $info = model('app\api\model\service\Address')->where(['id'=>$post['id'],'user_id'=>$uid])->find();
            !$info && $this->error('地址信息异常');
            \app\api\model\service\Address::destroy($post['id']);
            $this->success('地址信息已删除');
        }
        $this->error('接口异常');
    }

    /**
     * 地址详情
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info()
    {
        $id = input('id/d','');
        $info = model('app\api\model\service\Address')->where(['id'=>$id])->find();
        !$info && $this->error('地址信息异常');
        $this->success('信息返回成功',$info);
    }
}
